<?php

class Core_Model_DbTable_Shares extends YouNet_Db_Table
{
	const TABLE_NAME        = 'contest_shares';
    protected $_name        = self::TABLE_NAME;
    protected $_rowClass    = 'Core_Model_Share';
    
    const USING_BANNER_IMAGE = 0;
    const USING_UPLOAD_IMAGE = 1;
    
	private static $_instance;
	public static function getInstance()
	{
		if(is_null(self::$_instance))
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}
    
    public function getShareConfig($id_contest)
    {
        $result = $this->fetchRow(array('id_contest = ?' => $id_contest));
        if(is_null($result)){
            $result = $this->createRow();
        }
        return $result;
    }
    
    public function getShareContent($id_contest, $id_page){
        $sql = $this->select()->setIntegrityCheck(false)
                ->from(array('s' => self::TABLE_NAME))
                ->joinLeft(array('p' => Core_Model_DbTable_Pages::TABLE_NAME), 
                        's.id_contest = p.id_contest AND p.id_page = ' . $id_page,
                        array('page_name' => 'p.name_page'))
                ->where('s.id_contest = ?', $id_contest);
        $shareConfigRow = $this->fetchRow($sql);
        if(!empty($shareConfigRow)){
            if(!empty($shareConfigRow->page_name)){
                $shareConfigRow->title = sprintf("%s : %s", $shareConfigRow->page_name, $shareConfigRow->title);
            }
        } else {
            $contestRow = Core_Model_DbTable_Contests::getInstance()->getShareContest($id_contest, $id_page);
            $shareConfigRow = $this->createRow();
            if(!empty($contestRow)){
                $shareConfigRow->saveShareConfig(array(
                    'id_contest' => $contestRow->id,
                    'title' => $contestRow->title,
                    'description' => strip_tags($contestRow->description),
                    'using_image' => self::USING_BANNER_IMAGE
                ));
                $shareConfigRow->title = sprintf("%s : %s", $contestRow->name_page, $contestRow->title);
                $shareConfigRow->description = strip_tags($contestRow->description);
            }
        }
        return $shareConfigRow;
    }
}
